package com.bao.system.mapper;

import com.bao.system.entity.BUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * <p>
 * 用户表 Mapper 接口
 * </p>
 *
 * @author bao
 * @since 2021-06-03
 */
@Repository
public interface UserMapper extends BaseMapper<BUser> {

    @Select("select * from tb_user")
    List<BUser> allUsers();

    @Select("select * from tb_user where id = #{id}")
    BUser getUserById(Long id);

    @Select("select u.`id`, `username`, `nickname`, `email`, `avatar`, `phone_number`, `status`," +
            "      u.`create_time`, u.`modified_time`, `sex`, `salt`, `type`, `password`, `birth`," +
            "      `department_id`, `deleted`,d.name as name" +
            "      from tb_user u" +
            "      inner join tb_department d" +
            "      on u.department_id = d.id" +
            "      ${ew.customSqlSegment}")
    IPage<BUser> findUserPage(Page<BUser> page, @Param(Constants.WRAPPER) QueryWrapper<BUser> wrapper);

    @Update("update tb_user u  set u.`status` = #{status} where u.id = #{id} ")
    void editUser(Long id, Integer status);

    @Update("update tb_user u  set u.`department_id` = #{departmentId} where u.id = #{id} ")
    void editUserDep(Long id, Long departmentId);

    @Delete("delete from tb_user where tb_user.id = #{id}")
    void deleUser(Long id);

    @Select("select * from tb_user where username = #{username} and `password` = #{password}")
    BUser login(String username, String password);

    @Select("select * from tb_user where username = #{username}")
    BUser selectOneByUsername(String username);

//    @Select("select " +
//            "d.code " +
//            "FROM" +
//            "tb_department d, tb_user u " +
//            "where " +
//            "u.username = #{username} and d.id=u.department_id")
//    List<String> getRoleCodeByUserName(String username);

    /*通过用户名去查询user_id，并利用查询到的id去找到对应的权限角色*/
    @Select("select " +
            "r.code " +
            "FROM " +
            "tb_user_role ur " +
            "LEFT JOIN tb_user u on ur.user_id = u.id " +
            "LEFT JOIN tb_role r on ur.role_id = r.id " +
            "where " +
            "u.username = #{username}")
    List<String> getRoleCodeByUserName(String username);


}
